//
// file : show_dbg.c
// date : 4/4/05
//
//
// 1) create a shared memory block
// 2) show logs from it
// 
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>

#include <unistd.h>
#include <string.h>
#include "ring_buf.h"

#include <signal.h>


#define  MY_SHM_KEY  ((key_t)0x0000f0a0)

int loop = 1;


void crtl_c(int sig)
{
    loop=0;
}

void* att_shm(key_t key)
{
    int       e;
    void     *shmpt;
	int       shmid;

    e = shmget(/*IPC_PRIVATE*/key, 0, 0);

	if( -1 == e )
	{
		printf("Open shared memeory error(%d) Run application first.\n",
              errno);
		return 0;
	}

	shmid = e;

	shmpt = shmat(shmid, 0, 0);

	if( 0 == shmpt )
	{
		printf("shmat() error=%d\n", errno);
	}

	return shmpt;
}

int det_shm(void *pt)
{
	int e;

	if( pt )
	{
		e = shmdt(pt);
		if( -1 == e )
		{
			printf(" shmdt(%x) error=%d\n", (unsigned int)pt, errno);
		}
	}

	return e;
}



int main(int argc, char *argv[])
{
	char *logs;
    int  n;
	ring_t  *rb;
    char   buf[1024];
    msg_t  *msg;

	signal(SIGINT, crtl_c);
	signal(SIGTERM, crtl_c);

	logs = (char*)att_shm(MY_SHM_KEY);

	printf(" logs at (%x)\n", (unsigned int)logs);

    n = 0;

	if( logs == 0 ) goto out;

    rb = (ring_t *)logs;

	msg = (msg_t *)buf;

    while ( loop )
	{
		sleep(1);
        
		do
		{
			msg->len = 1020;

            n = rb_read(rb, msg);
		
            if( n > 0 ) fwrite((char*)(msg+1), 1, n-4, stdout);

		} while ( n > 0 );
	}

 out:
    det_shm((void*)logs);

	return 0;
}
